package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 42
 * @date 2025/3/25
 * @Description
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @Override
    @Transactional
    public Result add(DishDTO dishDto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto,dish);

        //插入菜品，主键返回
        dishMapper.insertDish(dish);

        //更新主键
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
        }

        //插入口味数据
        dishFlavorMapper.insertDishFlavorBatch(flavors);
        String key = RedisConstant.DISH_KEY+dishDto.getCategoryId();

        cleanCache(key);

        return Result.success();
    }

    /**
     * 菜品分页
     * @param queryDTO
     * @return
     */
    @Override
    public Result<PageResult> page(DishPageQueryDTO queryDTO) {

        PageHelper.startPage(queryDTO.getPage(),queryDTO.getPageSize());

        List<DishVO> info = dishMapper.page(queryDTO);

        PageInfo<DishVO> pageInfo = new PageInfo<>(info);
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());

        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public Result deleteBatch(List<Long> ids) {
        //1.查询菜品关联套餐
        List<SetmealDish> setmealInfo = setmealDishMapper.selectSetmealDish(ids);
        //2.判断是否有关联套餐
        if(!setmealInfo.isEmpty()){
            //3.有，则返回错误信息
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //4.无，则查询菜品是否起售状态
        List<Dish> dishes = dishMapper.selectStatus(ids, StatusConstant.ENABLE);
        if(!dishes.isEmpty()){
            //5.起售状态，返回错误信息
            return Result.error(MessageConstant.DISH_ON_SALE);
        }
        //6.非起售状态，删除菜品
        dishMapper.deleteBatch(ids);

        //7.删除菜品风味（加事务，确保一致）
        dishFlavorMapper.deleteBatch(ids);

        String key = "dish*";
        cleanCache(key);

        return Result.success();
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> selectDishInfo(Long id) {

        DishVO dishVo = dishMapper.selectDishInfo(id);

        List<DishFlavor>  flavors =  dishFlavorMapper.selectFlavor(id);
        dishVo.setFlavors(flavors);
        return Result.success(dishVo);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public Result updateDishInfo(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //1.修改菜品信息
        dishMapper.update(dish);
        //2.删除原有风味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //3.批量添加flavors
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            dishFlavorMapper.insertDishFlavorBatch(flavors);

        }

        String key = "dish*";
        cleanCache(key);


        return Result.success();
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectFlavor(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 起售或禁售菜品
     * @param id
     * @param status
     * @return
     */
    @Override
    public Result startOrStop(Long id, Integer status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        String key = "dish*";
        cleanCache(key);
        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    public void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
